﻿using UnityEngine;
using Zero;

/// <summary>
/// 元素反应：激化
/// </summary>
public class ElementQuicken : IElementReaction
{
    private readonly IElementHolder _holder;
    private readonly IElementAura _grassAura;
    private readonly IElementAura _electricAura;
    private readonly IElementAura _quickenAura;

    public ElementQuicken(IElementHolder holder)
    {
        _holder = holder;
        _grassAura = _holder.GetElementAura("草");
        _electricAura = _holder.GetElementAura("雷");
        _quickenAura = _holder.GetElementAura("激化");
    }

    public void Reaction(TriggerElementData triggerElementData)
    {
        if (_quickenAura.Gauge > 0f)
        {
            if (triggerElementData.ElementType == ElementType.Electric)
            {
                ServiceLocator.Get<IWorldNumberService>()
                    .CreateElementReaction(_holder.Owner.transform.position, "超激化");
                triggerElementData.DamageBoosters.Add(new ElementDamageBooster("超激化", 1.15f));
            }

            if (triggerElementData.ElementType == ElementType.Grass)
            {
                ServiceLocator.Get<IWorldNumberService>()
                    .CreateElementReaction(_holder.Owner.transform.position, "蔓激化");
                triggerElementData.DamageBoosters.Add(new ElementDamageBooster("蔓激化", 1.25f));
            }
        }

        if (TrySyntheticQuickenGauge(triggerElementData, out var quickenGauge))
        {
            ServiceLocator.Get<IWorldNumberService>()
                .CreateElementReaction(_holder.Owner.transform.position, "原激化");
            _quickenAura.Attach(Mathf.Max(_quickenAura.Gauge, quickenGauge), triggerElementData.Source);

            triggerElementData.IsTriggered = true;
        }
    }

    private bool TrySyntheticQuickenGauge(TriggerElementData triggerElementData, out float quickenGauge)
    {
        if (triggerElementData.ElementType == ElementType.Electric)
        {
            if (_grassAura.Gauge > 0f)
            {
                var minGauge = Mathf.Min(_grassAura.Gauge, triggerElementData.Gauge);
                _grassAura.Gauge -= minGauge;
                triggerElementData.Gauge -= minGauge;
                quickenGauge = minGauge;
                return true;
            }
        }

        if (triggerElementData.ElementType == ElementType.Grass)
        {
            if (_electricAura.Gauge > 0f)
            {
                var minGauge = Mathf.Min(_electricAura.Gauge, triggerElementData.Gauge);
                _electricAura.Gauge -= minGauge;
                triggerElementData.Gauge -= minGauge;
                quickenGauge = minGauge;
                return true;
            }
        }

        quickenGauge = 0f;
        return false;
    }
}